package fr.inserm.umr915.libjson.bdb;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;

import fr.inserm.umr915.libjson.Node;
import fr.inserm.umr915.libjson.NodeFactory;

import com.sleepycat.bind.tuple.TupleInput;
import com.sleepycat.bind.tuple.TupleOutput;

public class NodeBinding extends AbstractNodeBinding
	{
	private NodeFactory factory;
	
	public NodeBinding()
		{
		this(new NodeFactory());
		}
	
	public NodeBinding( NodeFactory factory)
		{
		this.factory=factory;
		}
	
	public NodeFactory getNodeFactory()
		{
		return this.factory;
		}
	
	@Override
	public Node entryToObject(TupleInput in)
		{
		try {
			DataInputStream di=new DataInputStream(new ByteArrayInputStream(
				in.getBufferBytes(),
				in.getBufferOffset(),
				in.getBufferLength()
				));
			Node n= getNodeFactory().read(di);
			di.close();
			return n;
			} 
		catch (Exception e)
			{
			throw new RuntimeException(e);
			}
		}

	@Override
	public void objectToEntry(Node n, TupleOutput out)
		{
		try
			{
			ByteArrayOutputStream baos=new ByteArrayOutputStream();
			DataOutputStream dout= new DataOutputStream(baos);
			n.write(dout);
			dout.flush();
			out.write(baos.toByteArray());
			} 
		catch (Exception e)
			{
			throw new RuntimeException(e);
			}
		}
}
